﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using jSLApp.Client.MainService;
using jSLApp.Client.Workflow;
using jSLCore.Client.Presentation.Authorization;
using jSLCore.Client.Presentation.BaseControl;
using jSLCore.Client.Presentation.BaseControl.DialogMessage;
using jSLCore.Utility.Extensions;

namespace jSLApp.Client.Forms
{
    /// <summary>
    /// Form for users viewing and for
    /// </summary>
    public partial class UserAbout : DialogControl
    {

        /// <summary>
        /// Only for designers
        /// </summary>
        public UserAbout()
        {
            InitializeComponent();
        }

        private string _login;
        public UserAbout(string login)
        {
            InitializeComponent();
            _login = login;
        }

        public override void LoadInitialData()
        {
            LoadUser();
        }

        private void LoadUser()
        {
            DoWork("Загрузка информации",(sender, args) =>
                                             {
                                                 args.Result = Communication.Proxy.GetProject(args.String);
                                             },(o, eventArgs) =>
                                                                   {
                                                                       if(eventArgs.Error==null)
                                                                           SetDataContext((User) eventArgs.Result);
                                                                   },_login);
        }



        public void SetDataContext(User user)
        {
            User = user;
            LoadUserImage();
            LoadUserMusics();
            Bind();
        }

        private void LoadUserMusics()
        {
            DoWork("Загрузка треков", (sender, args) =>
                                          {
                                              args.Result = Communication.Proxy.GetUserMusicList(args.String);
                                          }, (o, eventArgs) =>
                                                                 {
                                                                     if (eventArgs.Error == null)
                                                                         grid.ItemsSource = (IEnumerable) eventArgs.Result;
                                                                 }, User.Login);
        }

        private User User
        {
            get {  return (User) DataContext; }
            set { DataContext = value; }
        }

        private void LoadUserImage()
        {
            DoWork(true, (o, eventArgs) =>
            {
                eventArgs.Result = Communication.Proxy.GetUserImage(eventArgs.String);
            }, (sender1, completedEventArgs) =>
            {
                pic.Source =
                    ((byte[])completedEventArgs.Result).
                        ConvertToImageSource();
            }
                   , User.Login);
        }

        #region Appearence

        private void changeName_Clicked(object sender, RoutedEventArgs e)
        {
            if(User.Login!=jSecurity.Login)return;

            var hyperlinkButton = sender as HyperlinkButton;
            var dlg = new jAskForStringBox("Введите новый псевдоним:", (string)hyperlinkButton.Content, false);
            dlg.ShowDialog(delegate(object o, object data)
            {
                var str = data as string;
                if (string.IsNullOrEmpty(str))
                {
                    ErrorBox.ShowDialog("Необходимо указать новый псеводним.");
                    return;
                }

                DoWork("Смена псевдонима", (sender1, args) =>
                {
                    Communication.Proxy.ChangeCurrentUserName(args.String);
                }, (o1, eventArgs) =>
                {
                    if (eventArgs.Error == null)
                    {
                        hyperlinkButton.
                            Content = str;
                        InfoBox.ShowDialog("Псевдоним изменен");
                    }
                }, str);

            }, this);
        }

        private void changePic_Clicked(object sender, MouseButtonEventArgs e)
        {
            if (User.Login != jSecurity.Login) return;

            var dlg = new OpenFileDialog();
            if (dlg.ShowDialog().GetValueOrDefault(false))
            {
                var stream = dlg.File.OpenRead();
                if (stream.Length > 1000000)
                {
                    ErrorBox.ShowDialog("Размер файла слишком большой");
                    return;
                }

                var bs = new byte[stream.Length];
                stream.Read(bs, 0, (int)stream.Length);
                stream.Close();

                DoWork("Смена изображения", (o, args) =>
                {
                    Communication.Proxy.ChangePictureForCurrentUser((byte[])args.Argument);
                }, (sender1, eventArgs) =>
                {
                    if (eventArgs.Error == null)
                    {
                        //pic.Source = bs.ConvertToImageSource(); it can be bug, 'cause server will convert it..
                        LoadUserImage();
                    }
                }, bs);
            }
        }

        #endregion
       

        #region dialog

        public override bool IsStandartOkCancelEnabled
        {
            get { return true; }
        }

        public override bool AutoSize
        {
            get { return false; }
        }

        public override bool IsOkVisible
        {
            get { return false; }
        }

        public override object CancelContent
        {
            get { return "Закрыть"; }
        }

        

        #endregion

        private void sendMessage(object sender, RoutedEventArgs e)
        {
            var dlg = new NewMessage(User.Login,User.NameText);
            dlg.ShowDialog(this);
        }

        private void mail_Clicked(object sender, RoutedEventArgs e)
        {
            DoWork("Изменение настроек уведомлений",(o, args) => Communication.Proxy.ChangeMailSettings(args.String,
                                                                                                        (bool) args.Params[1],
                                                                                                        (bool) args.Params[2],
                                                                                                        (bool) args.Params[3]),(sender1, eventArgs) =>
                                                              {
                                                                  if(eventArgs.Error==null)
                                                                  {
                                                                      InfoBox.ShowDialog("Настройки уведомлений изменены",500,this);
                                                                  }
                                                                  else
                                                                  {
                                                                      var checkBox = (CheckBox)sender;
                                                                      checkBox.IsChecked = !checkBox.IsChecked;
                                                                  }
                                                              },
                                                        User.Login,
                                                        newsCheck.IsChecked,
                                                        messageCheck.IsChecked,
                                                        commentCheck.IsChecked);
        }

        private void chat_Clicked(object sender, RoutedEventArgs e)
        {
            DoWork("Изменение настроек чата",(o, args) =>
                                                 {
                                                     Communication.Proxy.SetDontShowChat((bool) args.Argument);
                                                 },(sender1, eventArgs) =>
                                                       {
                                                           if(eventArgs.Error==null)
                                                           {
                                                               InfoBox.ShowDialog("Настройки чата изменены",500,this);
                                                               ChatController.AutoUpdate = (bool) (!chatCheck.IsChecked);
                                                           }
                                                           else
                                                           {
                                                               chatCheck.IsChecked = !chatCheck.IsChecked;
                                                           }
                                                       },chatCheck.IsChecked);
        }

        private void goto_userAdmin(object sender, RoutedEventArgs e)
        {
            var dlg = new UserDetail(User.Login);
            dlg.ShowDialog(delegate(object o, object data) { LoadInitialData(); }, this);
        }

     
    }
}
